#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Mikan Reuest Module

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_41"
__date__    = "2014/03/16"
__license__ = 'LGPL'

# ------------------------------------------------------------
## Import Section
# ------------------------------------------------------------
# Python
import os
import re
import cgi, shutil
import base64
import traceback
import locale

# pytz
try:
	import pytz
	is_pytz = True
except:
	is_pytz = False
import logging

# woothee
try:
	import woothee
	is_woothee = True
except:
	is_woothee = False

# ESiPC
from esipc import ESiPCProperty

# Mikan
from mikan.core import AbstractMikan, MIKAN_HTTP_HEADER, MIKAN_INI, MIKAN
from mikan.kvs import new_mikan_kvs
from mikan.rdb import new_mikan_rdb
from mikan.orm import new_mikan_orm
from mikan.preference.kvs import MikanKVSPreference
from mikan.session import MikanUserSession

# ------------------------------------------------------------
## Variable Section
# ------------------------------------------------------------

is_windows = False

try:
    os.uname()
except:
    is_windows = True

class MIKAN_REQUEST(MIKAN):
	MIKAN_LICENSE = __license__

# ------------------------------------------------------------
## Function Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Class Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Mikan リクエストクラス
#
class AbstractMikanRequest(AbstractMikan, MIKAN_REQUEST):

	# ----------------------------------------------------
	## コンストラクタ
	#  @param self クラス自身
	def __init__(self):
		super(AbstractMikanRequest, self).__init__()

# ------------------------------------------------------------
## Mikan リクエストクラス
#
class AbstractMikanHttpRequest(AbstractMikanRequest, MIKAN_HTTP_HEADER):

	# ----------------------------------------------------
	## 環境変数 フィールドゲッター
	# @return 取得した値
	def get_environ(self):
		return None

	# ----------------------------------------------------
	## 環境変数 取得
	# @param name 環境変数名
	# @param default デフォルト値
	# @return 取得した値
	def get_environ_value(self, name, default):
		value = None

		try:
			value = self.environ[name]

			if value != None:
				return value
		except:
			pass

		try:
			value = self.environ[name.upper()]

			if value != None:
				return value
		except:
			pass

		try:
			value = self.environ[name.lower()]

			if value != None:
				return value
		except:
			pass

		return default

#	TODO
#	def __getitem__(self, index):
#		return get_environ_value()[index.lower()]
#
#	def __setitem__(self, index, value):
#		pass

	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_remote_host(self):
		return self.get_environ_value(self.NAME_REMOTE_HOST, None)

	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_http_referer(self):
		return self.get_environ_value(self.NAME_HTTP_REFERER, None)

	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_remote_addr(self):
		return self.get_environ_value(self.NAME_REMOTE_ADDR, None)

	def get_remote_port(self):
		return self.get_environ_value(self.NAME_REMOTE_PORT, None)

	def get_remote_user(self):
		return self.get_environ_value(self.NAME_REMOTE_USER, None)

	def get_user_agent(self):
		return self.get_environ_value(self.NAME_HTTP_USER_AGENT, None)

	def get_path_info(self):
		return self.get_environ_value(self.NAME_PATH_INFO, "")

	def get_real_path(self):
		return self.get_path_info()

	def get_script_name(self):
		return self.get_environ_value(self.NAME_SCRIPT_NAME, "")

	def get_method(self):
		value = self.get_environ_value(self.NAME_REQUEST_METHOD, "")
		if value:
			return value.upper()
		return ""

	def get_query_string(self):
		return self.get_environ_value(self.NAME_QUERY_STRING, "")

	def is_head_method(self):
		return self.method == self.VALUE_REQUEST_METHOD_HEAD

	def is_get_method(self):
		return self.method == self.VALUE_REQUEST_METHOD_GET

	def is_post_method(self):
		return self.method == self.VALUE_REQUEST_METHOD_POST

	def get_http_authhorization(self):
		return self.get_environ_value(self.NAME_HTTP_AUTHORIZATION, "")

	def get_server_port(self):
		return self.get_environ_value(self.NAME_SERVER_PORT, "80")

	def get_server_protocol(self):
		return self.get_environ_value(self.NAME_SERVER_PROTOCOL, "")

	def get_server_software(self):
		return self.get_environ_value(self.NAME_SERVER_SOFTWARE, "")

	def get_gateway_interface(self):
		return self.get_environ_value(self.NAME_GATEWAY_INTERFACE, "")

	def get_http_cookie(self):
		return self.get_environ_value(self.NAME_HTTP_COOKIE, "")

	def get_auth_type(self):
		return self.get_environ_value(self.NAME_AUTH_TYPE, "")

	def get_http_accept(self):
		return self.get_environ_value(self.NAME_HTTP_ACCEPT, "")

	def get_http_accept_encoding(self):
		return self.get_environ_value(self.NAME_HTTP_ACCEPT_ENCODING, "")

	def get_http_accept_language(self):
		return self.get_environ_value(self.NAME_HTTP_ACCEPT_LANGUAGE, "")

	def get_http_connection(self):
		return self.get_environ_value(self.NAME_HTTP_CONNECTION, "")

	def get_http_host(self):
		return self.get_environ_value(self.NAME_HTTP_HOST, "")

	def get_https(self):
		return self.get_environ_value(self.NAME_HTTPS, False)

	def __init__(self):
		super(AbstractMikanHttpRequest, self).__init__()

	# ----------------------------------------------------
	## Property
	environ = ESiPCProperty(get_environ, None, None)
	method = ESiPCProperty(get_method, None, None)
	isheadmethod = ESiPCProperty(is_head_method, None, None)
	isgetmethod = ESiPCProperty(is_get_method, None, None)
	ispostmethod = ESiPCProperty(is_post_method, None, None)
	https = ESiPCProperty(get_https, None, None)
	httphost = ESiPCProperty(get_http_host, None, None)
	httpconnection = ESiPCProperty(get_http_connection, None, None)
	httpacceptencoding = ESiPCProperty(get_http_accept_encoding, None, None)
	httpacceptlanguage = ESiPCProperty(get_http_accept_language, None, None)
	httpaccept = ESiPCProperty(get_http_accept, None, None)
	authtype = ESiPCProperty(get_auth_type, None, None)
	httpcookie = ESiPCProperty(get_http_cookie, None, None)
	httpauthhorization = ESiPCProperty(get_http_authhorization, None, None)
	httpreferer = ESiPCProperty(get_http_referer, None, None)
	gatewayinterface = ESiPCProperty(get_gateway_interface, None, None)
	serversoftware = ESiPCProperty(get_server_software, None, None)
	serverprotocol = ESiPCProperty(get_server_protocol, None, None)
	serverport = ESiPCProperty(get_server_port, None, None)
	pathinfo = ESiPCProperty(get_path_info, None, None)
	realpath = ESiPCProperty(get_real_path, None, None)
	useragent = ESiPCProperty(get_user_agent, None, None)
	remoteaddr = ESiPCProperty(get_remote_addr, None, None)
	remoteport = ESiPCProperty(get_remote_port, None, None)
	remoteuser = ESiPCProperty(get_remote_user, None, None)
	scriptname = ESiPCProperty(get_script_name, None, None)
	querystring = ESiPCProperty(get_query_string, None, None)
	remotehost = ESiPCProperty(get_remote_host, None, None)

# ------------------------------------------------------------
## Mikan Database Request Class
#
class AbstractMikanLocaleRequest(AbstractMikanHttpRequest):

	def set_timezone(self, value):
		self.FTimezone = value

	def get_timezone(self):
		return self.FTimezone

	def set_encode(self, value):
		self.FEncode = value

	def get_encode(self):
		return self.FEncode

	def set_lang(self, value):
		self.FLang = value

	def get_lang(self):
		return self.FLang

	def set_locale(self, value):
		self.FLocale = value

	def get_locale(self):
		return self.FLocale

	def __init__(self):
		super(AbstractMikanLocaleRequest, self).__init__()

		self.FTimezone = None
		self.FEncode = "UTF-8"
		self.FLang = "ja"
		self.FLocale = locale.getdefaultlocale()

	def init_timezone(self):
		try:
			self.FTimezone = pytz.timezone('Asia/Tokyo')
		except:
			self.FTimezone = None

	def init_lang(self):
		try:
			lang = self.httpacceptlanguage
			langs = lang.split(",")
			self.FLang = langs[0].split(";")[0]
		except:
			self.FLang = "ja"

	def init_locale(self):
		# default reset
		try:
			locale.setlocale(locale.LC_ALL, '')
		except:
			self.logger.debug(traceback.format_exc())

		try:
			if is_windows:
				if self.lang == "ja":
					locale.setlocale(locale.LC_ALL, ('Japanese_Japan', '932'))
				elif self.lang == "ja-jp":
					locale.setlocale(locale.LC_ALL, ('Japanese_Japan', '932'))
				elif self.lang == "en":
					locale.setlocale(locale.LC_ALL, ('English_United States', '1252'))
				elif self.lang == "en-us":
					locale.setlocale(locale.LC_ALL, ('English_United States', '1252'))
			else:
				if self.lang == "ja":
					locale.setlocale(locale.LC_ALL, "ja_JP.UTF-8")
				elif self.lang == "ja-jp":
					locale.setlocale(locale.LC_ALL, "ja_JP.UTF-8")
				elif self.lang == "en":
					locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
				elif self.lang == "en-us":
					locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

			self.FLocale = locale.getlocale()
		except:
			self.logger.debug(locale.getlocale())
			self.logger.debug(traceback.format_exc())

		self.logger.debug(self.FLocale)

	# ----------------------------------------------------
	## Property
	lang = ESiPCProperty(get_lang, set_lang, None)
	locale = ESiPCProperty(get_locale, set_locale, None)
	timezone = ESiPCProperty(get_timezone, set_timezone, None)
	encode = ESiPCProperty(get_encode, set_encode, None)

class MikanAgent(object):

	def __init__(self, wp=None):
		super(MikanAgent, self).__init__()

		self.name = ""
		self.os = ""
		self.category = ""
		self.version = ""
		self.vendor = ""

		if wp != None:
			if wp.has_key("name"):
				self.name = wp["name"]
			if wp.has_key("os"):
				self.os = wp["os"]
			if wp.has_key("category"):
				self.category = wp["category"]
			if wp.has_key("version"):
				self.version = wp["version"]
			if wp.has_key("vendor"):
				self.vendor = wp["vendor"]

# ------------------------------------------------------------
## Mikan User Agent Request Class
#
class AbstractMikanUserAgentRequest(AbstractMikanLocaleRequest):

	def get_agent(self):
		if self.FAgent == None:
			try:
				self.FAgent = MikanAgent(woothee.parse(self.useragent))
			except:
				self.FAgent = MikanAgent()

		return self.FAgent

	def get_agent_name(self):
		return self.agent.name

	def get_agent_os(self):
		return self.agent.os

	def get_agent_category(self):
		return self.agent.category

	def get_agent_version(self):
		return self.agent.version

	def get_agent_vendor(self):
		return self.agent.vendor

	def __init__(self):
		super(AbstractMikanUserAgentRequest, self).__init__()

		self.FAgent = None

	# ----------------------------------------------------
	## Property
	agent = ESiPCProperty(get_agent, None, None)
	agentname = ESiPCProperty(get_agent_name, None, None)
	agentos = ESiPCProperty(get_agent_os, None, None)
	agentcategory = ESiPCProperty(get_agent_category, None, None)
	agentversion = ESiPCProperty(get_agent_version, None, None)
	agentvendor = ESiPCProperty(get_agent_vendor, None, None)

# ------------------------------------------------------------
## Mikan Database Request Class
#
class AbstractMikanDatabaseRequest(AbstractMikanUserAgentRequest):

	def __init__(self):
		super(AbstractMikanDatabaseRequest, self).__init__()

		self.FKVSs = {}
		self.FRDBs = {}
		self.FORMs = {}

	def get_dbs(self):
		t = self.get_config_value("db", "main", "orm")
		if t == "rdb":
			return self.rdbs
		if t == "orm":
			return self.orms
		if t == "kvs":
			return self.kvss

		return None

	def get_rdbs(self):
		return self.FRDBs

	def get_kvss(self):
		return self.FKVSs

	def get_orms(self):
		return self.FORMs

	def get_db(self):
		t = self.get_config_value("db", "main", "orm")

		if t == "rdb":
			return self.rdb
		if t == "orm":
			return self.orm
		if t == "kvs":
			return self.kvs

		return None

	def _setup_db(self, new, name, config):
		n = name
		if config != "-":
			n = "%s_%s" % (name, config)

		if self.islogdebug:
			self.logger.debug(new)
			self.logger.debug(n)
			self.logger.debug(config)


		try:
			t = self.get_config_value(n, "type")
			if t:
				rdb = new(self, t)
				if rdb:
					rdb.setup(self.config, n)
					return rdb
		except:
			self.logger.warn(traceback.format_exc())

		return False

	def setup_rdb(self, config):
		return self._setup_db(new_mikan_rdb, "rdb", config)

	def setup_kvs(self, config):
		return self._setup_db(new_mikan_kvs, "kvs", config)

	def setup_orm(self, config):
		return self._setup_db(new_mikan_orm, "orm", config)

	def get_rdb(self, config="-", init=True):
		if self.rdbs.has_key(config):
			return self.rdbs[config]

		if init:
			self.rdbs[config] = self.setup_rdb(config)
			return self.rdbs[config]

		return None

	def get_kvs(self, config="-", init=True):
		if self.kvss.has_key(config):
			return self.kvss[config]

		if init:
			self.kvss[config] = self.setup_kvs(config)
			return self.kvss[config]

		return None

	def get_orm(self, config="-", init=True):
		if self.orms.has_key(config):
			return self.orms[config]

		if init:
			self.orms[config] = self.setup_orm(config)
			return self.orms[config]

		return None

	def _destroy_db(self, l):
		for i in l.values():
			try:
				if (i != None):
					i.close()
			except:
				# ログ
				if self.islogdebug:
					self.logger.debug(traceback.format_exc())
		try:
			l.clear()
		except:
			# ログ
			if self.islogdebug:
				self.logger.debug(traceback.format_exc())

	def destroy(self):
		try:
			if (self.rdbs != None):
				self._destroy_db(self.rdbs)
		except:
			# ログ
			if self.islogdebug:
				self.logger.debug(traceback.format_exc())

		try:
			if (self.orms != None):
				self._destroy_db(self.orms)
		except:
			# ログ
			if self.islogdebug:
				self.logger.debug(traceback.format_exc())

		try:
			if (self.kvss != None):
				self._destroy_db(self.kvss)
		except:
			# ログ
			if self.islogdebug:
				self.logger.debug(traceback.format_exc())

	# ----------------------------------------------------
	## Property
	db = ESiPCProperty(get_db, None, None)
	rdb = ESiPCProperty(get_rdb, None, None)
	orm = ESiPCProperty(get_orm, None, None)
	kvs = ESiPCProperty(get_kvs, None, None)

	dbs = ESiPCProperty(get_dbs, None, None)
	rdbs = ESiPCProperty(get_rdbs, None, None)
	orms = ESiPCProperty(get_orms, None, None)
	kvss = ESiPCProperty(get_kvss, None, None)

# ------------------------------------------------------------
## Mikan リクエストクラス
#
class MikanRequest(AbstractMikanDatabaseRequest):

	# ----------------------------------------------------
	## ログイン済 プロパティ
	def is_logined(self):
		return self.username != None

	# ----------------------------------------------------
	## システム管理者かどうか プロパティ
	def is_sa(self):
		return self.username == "sonohara"

	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_user_mail(self):
		try:
			return self.usersession.values["mail"]
		except:
			return None

	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_user_name(self):
		a = self.remoteuser
		if a != None:
			return a

		try:
			a = self.httpauthhorization
			b = a.split(' ')[1]
			c = base64.standard_b64decode(b)
			return c.split(':')[0]
		except Exception:
			self.logger.debug(traceback.format_exc())

		return None
	# ----------------------------------------------------
	## ユーザ名 プロパティ
	def get_group_name(self):
		a = self.remoteuser
		if a != None:
			return a

		return None

	# ----------------------------------------------------
	## 例外 フィールドゲッター
	# @return 取得した値
	def get_exceptions(self):
		return self.FExceptions

	# ----------------------------------------------------
	## 例外 ありかどうか
	# @return 取得した値
	def is_exceptions(self):
		return len(self.FExceptions) > 0

	# ----------------------------------------------------
	## ユーザ セッション プロパティ
	def get_user_session(self):
		return self.FUserSession

	# ----------------------------------------------------
	## Webアプリケーション プロパティ
	def get_webapp(self):
		return self.FWebapp

	# ----------------------------------------------------
	## コンストラクタ
	#  @param self クラス自身
	#  @param webapp Webアプリケーション
	def __init__(self, webapp):
		self.FWebapp = webapp

		self.FStatus = 200
		self.FHeaders = {}
		self.FContent = []
		self.FUseEncode = True
		self.FParams = None
		self.FApps = None
		self.FAppName = None
#		self.FKVS = None
#		self.FRDB = None
#		self.FORM = None

		self.FExceptions = []

		self.FConfigSuffix = None

		self.FUserSession = MikanUserSession(self)
		super(MikanRequest, self).__init__()

		self.init_timezone()
		self.init_lang()
		self.init_locale()

		# アクセスログ
		try:
			self.acces_logs()
		except:
			self.logger.debug(traceback.format_exc())

	def acces_logs(self):
		log = logging.getLogger(MIKAN_INI.LOG_ACCESS)
		self.acces_log(log)

	def acces_log(self, log):
		remote = self.remotehost
		ra = self.remoteaddr
		user = self.username
		if user == None:
			user = "-"
		method = self.method
		url = self.pathinfo
		agent = self.useragent
		hr = self.httpreferer

		log.info(u"|%s|%s|%s|%s|%s|%s|%s" % (agent, method, url, ra, remote, hr, user))

	def destroy(self):
		super(MikanRequest, self).destroy()

	def get_config(self):
		return self.webapp.config

	def get_mikan_root(self):
		return self.webapp.mikanroot

	def set_config_suffix(self, value):
		self.FConfigSuffix = value

	def get_config_suffix(self):
		return self.FConfigSuffix

	def get_config_value(self, section, name, default=None):
		# 変数初期化
		suffix = self.configsuffix
		result = None

		# 指定設定読み込み
		if suffix != None:
			try:
				s = u"%s_%s" % (section, suffix)
				result = self.config.get_string(name, default, l=self.locale, section=s)
			except:
				pass

			if (result != None) and (result  != ""):
				return result

		# デフォルトサイト設定読み込み
		try:
			return self.config.get_string(name, default, l=self.locale, section=section)
		except:
			pass
		if result != None:
			return result

		# 結果が無い(None)場合デフォルト値
		return default

	def set_use_encode(self, value):
		self.FUseEncode = value

	def get_use_encode(self):
		return self.FUseEncode

	def set_status(self, value):
		self.FStatus = value

	def get_status(self):
		return self.FStatus

	def _param_list(self, form, key):
		ls = form.getvalue(key, "")

		l = []
		for v in ls:
			l.append(self._param_str(form, key, v))

		return l

	def _param_str(self, form, key, value=None):
		v = value
		if v == None:
			try:
				v = form[key].value
			except:
				self.logger.debug(traceback.format_exc())
				return None

		if v:
			try:
				return v.decode("utf-8")
			except:
				self.logger.debug(traceback.format_exc())
				return v
		return None

	def _params(self, form):
		self.logger.debug(form)
		self.logger.debug(form.keys())

		ps = {}
		for key in form.keys():
			if form[key] != None:
				try:
					if (isinstance(form[key], list)):
						ps[key] = self._param_list(form, key)
					elif isinstance(form[key], cgi.FieldStorage) or isinstance(form[key], cgi.MiniFieldStorage):
						f = False
						try:
							if (form[key].file != None) and (form[key].filename):
								f = True
						except:
							pass
						if f == False:
							ps[key] = self._param_str(form, key)
					else:
						ps[key] = form[key]
				except:
					self.logger.debug(traceback.format_exc())

		return ps

	def get_params(self):
		if (self.FParams == None):
			try:
				if (self.isgetmethod):
					self.FParams = self._params(dict(cgi.parse_qsl(self.querystring)))
				elif (self.ispostmethod):
					self.FParams = self._params(self.fieldstorage)
				else:
					self.FParams = {}
			except:
				self.logger.debug(traceback.format_exc())
				self.FParams = {}
			self.logger.debug(self.FParams)

		return self.FParams

	def get_param(self, name):
		value = self.params.get(name)

		self.logger.debug(value)
		return value

	def get_param_str(self, name, default):
		try:
			s = self.get_param(name)
			if s:
				return s
			return default
		except:
			self.logger.debug(traceback.format_exc())
			return default

	def get_param_int(self, name, default):
		try:
			s = self.get_param(name)
			return int(s, 10)
		except:
			self.logger.debug(traceback.format_exc())
			return default

	def get_param_boolean(self, name, default):
		try:
			p = self.get_param(name)
			self.logger.debug(p)
			if p == "True":
				return True
			elif p == "False":
				return False
			return default
		except:
			self.logger.debug(traceback.format_exc())
			return default

	def get_headers(self):
#		# TODO length
#		try:
#			if self.headers[MIKAN_HTTP_HEADER.NAME_CONTENT_LENGTH]:
#		except:
#			pass
#
#		try:
#			self.headers[MIKAN_HTTP_HEADER.NAME_CONTENT_LENGTH] = str(self.contentlength)
#		except:
#			pass
		return self.FHeaders

	def set_content(self, value):
		self.FContent = value

	def get_content(self):
		return self.FContent

	def get_content_length(self):
		l = 0

		for c in self.content:
			l += len(c)

		return l

	def set_content_type(self, value):
		v = value

		if self.useencode:
			v = v + "; charset=" + self.encode

		self.headers[MIKAN_HTTP_HEADER.NAME_CONTENT_TYPE] = v

	def get_content_type(self):
		return self.headers[MIKAN_HTTP_HEADER.NAME_CONTENT_TYPE]

	def parse_apps(self):
		p = re.compile(r'^' + self.appspath)
		a = self.realpath
		a = a.replace('_', '')
		a = a.replace('.', '_')
		t = p.sub("", a)
		p = re.compile(r'/')
		c = p.split(t)
		n = c[len(c)-1]

		c.pop()
		s = ""
		for g in c:
			if (g <> ""):
				s = s + "." + g

		if (s == ""):
			s = ".index"
		if (n == ""):
			n = "index"

		self.FAppName = n
		self.FApps = s

	def get_apps(self):
		if (self.FApps == None):
			self.parse_apps()
		return self.FApps

	def get_app_name(self):
		if (self.FAppName == None):
			self.parse_apps()
		return self.FAppName

	def get_apps_path(self):
		return self.get_config_value(MIKAN_INI.MIKAN, MIKAN_INI.APPS)

	def get_htdocs_url(self):
		return self.get_config_value(MIKAN_INI.MIKAN, MIKAN_INI.HTDOCS_URL)

	def get_image_url(self):
		return self.htdocsurl + "/images/"

	def get_css_url(self):
		return self.htdocsurl + "/css/"

	def get_js_url(self):
		return self.htdocsurl + "/js/"

	def get_htdocs_dir(self):
		return os.path.abspath(self.get_config_value(MIKAN_INI.MIKAN, MIKAN_INI.HTDOCS_DIR, ""))

	def get_site_host_name(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.HOSTNAME, self.httphost)

	def get_site_url(self):
		https = self.https
		hostname = self.sitehostname
		port = self.serverport
		if https == True:
			http = "https://%s/"
#			http = "https://%s%s/"
#			if port == "443":
#				port = ""
#			else:
#				port = ":" + port
		else:
			http = "http://%s/"
#			http = "http://%s%s/"
#			if port == "80":
#				port = ""
#			else:
#				port = ":" + port

		url = http % (hostname)

		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.URL,  url)

	def get_site_title(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.TITLE, "")

	def get_site_description(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.DESCRIPTION, "")

	def get_site_confidential(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.CONFIDENTIAL, "")

	def get_site_version(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.VERSION, "")

	def get_site_date(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.DATE, "")

	def get_site_system(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.SYSTEM, "")

	def get_site_copyright(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.COPYRIGHT, "")

	def get_site_auther(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.AUTHER, "")

	def get_site_logo(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.LOGO, "logo.png")

	def get_site_compatible(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.COMPATIBLE, None)

	def get_site_viewport(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.VIEWPORT, None)

	def get_site_pass_phrase(self):
		return self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.PASSPHRASE, "mikan")

	def get_site_rsa_public_key(self):
		try:
			return self.sitersaprivatekey.publickey()
		except:
			return None

	def get_site_rsa_private_key(self):
		try:
			return self.FSiteRSAPrivateKey
		except:
			key = self.get_config_value(MIKAN_INI.SITE, MIKAN_INI.RSAPRVITEKEY, None)
			try:
				import Crypto.PublicKey.RSA as RSA
			except:
				pass
			try:
				self.FSiteRSAPrivateKey = RSA.importKey(key, passphrase=self.sitepassphrase)
				return self.FSiteRSAPrivateKey
			except:
				pass
		return None

	def get_jss(self):
		try:
			return self.get_config_value("js", "default", None).split(',')
		except:
			return None

	def get_js_loadeds(self):
		try:
			return self.get_config_value("js-loaded", "default", None).split(',')
		except:
			return None

	def get_csss(self):
		try:
			return self.get_config_value("css", "default", None).split(',')
		except:
			return None

	def get_theme(self):
		try:
			return self.get_config_value("theme", "default", None)
		except:
			return None

	def get_mail_smtp_host(self):
		try:
			return self.get_config_value("mail", "smtp.host", None)
		except:
			return None

	def get_mail_encode(self):
		try:
			return self.get_config_value("mail", "encode", "UTF-8")
		except:
			return "UTF-8"

	def get_mail_dryrun(self):
		try:
			return self.get_config_value("mail", "dryrun", None)
		except:
			return True

	def get_field_storage(self):
		return cgi.FieldStorage()

	def file_to(self, name, path):
		self.logger.debug(path)
		form = self.fieldstorage

		if (form != None):
			if form.has_key(name):
				f = form[name]
				self.logger.debug(f)

				if f.file:
					wf = file(path + f.filename, 'wb')
					try:
						shutil.copyfileobj(f.file, wf)
					finally:
						wf.close()

	def init_preference(self):
		return MikanKVSPreference(self)

	def get_preference(self):
		try:
			if self.__dict__.has_key("FPreference"):
				return self.FPreference
		except:
			pass
		self.FPreference = self.init_preference()
		return self.FPreference

	# ----------------------------------------------------
	## Property
	preference = ESiPCProperty(get_preference, None, None)
	webapp = ESiPCProperty(get_webapp, None, None)
	config = ESiPCProperty(get_config, None, None)
	configsuffix = ESiPCProperty(get_config_suffix, set_config_suffix, None)
	usersession = ESiPCProperty(get_user_session, None, None)
	status = ESiPCProperty(get_status, set_status, None)
	fieldstorage = ESiPCProperty(get_field_storage, None, None)
	headers = ESiPCProperty(get_headers, None, None)
	theme = ESiPCProperty(get_theme, None, None)
	jsloadeds = ESiPCProperty(get_js_loadeds, None, None)
	jss = ESiPCProperty(get_jss, None, None)
	csss = ESiPCProperty(get_csss, None, None)
	htdocsurl = ESiPCProperty(get_htdocs_url, None, None)
	htdocsdir = ESiPCProperty(get_htdocs_dir, None, None)
	sitersapublickey = ESiPCProperty(get_site_rsa_public_key, None, None)
	sitersaprivatekey = ESiPCProperty(get_site_rsa_private_key, None, None)
	sitepassphrase = ESiPCProperty(get_site_pass_phrase, None, None)
	imageurl = ESiPCProperty(get_image_url, None, None)
	cssurl = ESiPCProperty(get_css_url, None, None)
	jsurl = ESiPCProperty(get_js_url, None, None)
	isexceptions = ESiPCProperty(is_exceptions, None, None)
	apps = ESiPCProperty(get_apps, None, None)
	appname = ESiPCProperty(get_app_name, None, None)
	appspath = ESiPCProperty(get_apps_path, None, None)
	islogined = ESiPCProperty(is_logined, None, None)
	issa = ESiPCProperty(is_sa, None, None)
	usermail = ESiPCProperty(get_user_mail, None, None)
	username = ESiPCProperty(get_user_name, None, None)
	groupname = ESiPCProperty(get_group_name, None, None)
	exceptions = ESiPCProperty(get_exceptions, None, None)
	params = ESiPCProperty(get_params, None, None)
	content = ESiPCProperty(get_content, set_content, None)
	contentlength = ESiPCProperty(get_content_length, None, None)
	contenttype = ESiPCProperty(get_content_type, set_content_type, None)
	sitehostname = ESiPCProperty(get_site_host_name, None, None)
	siteurl = ESiPCProperty(get_site_url, None, None)
	sitetitle = ESiPCProperty(get_site_title, None, None)
	sitedescription = ESiPCProperty(get_site_description, None, None)
	siteconfidential = ESiPCProperty(get_site_confidential, None, None)
	siteversion = ESiPCProperty(get_site_version, None, None)
	sitedate = ESiPCProperty(get_site_date, None, None)
	sitesystem = ESiPCProperty(get_site_system, None, None)
	sitecopyright = ESiPCProperty(get_site_copyright, None, None)
	siteauther = ESiPCProperty(get_site_auther, None, None)
	sitelogo = ESiPCProperty(get_site_logo, None, None)
	sitelogo = ESiPCProperty(get_site_logo, None, None)
	sitecompatible = ESiPCProperty(get_site_compatible, None, None)
	siteviewport = ESiPCProperty(get_site_viewport, None, None)
	useencode = ESiPCProperty(get_use_encode, set_use_encode, None)
	mailsmtphost = ESiPCProperty(get_mail_smtp_host, None, None)
	mailencode = ESiPCProperty(get_mail_encode, None, None)
	maildryrun = ESiPCProperty(get_mail_dryrun, None, None)


# ------------------------------------------------------------
## Main Section
# ------------------------------------------------------------
if __name__ == '__main__':
	pass

# ------------------------------------------------------------
